using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using LiteNetLib;
using Protocols;
using UnityEngine;
using UnityEngine.UI;

public class ApplicationCtrl : MonoBehaviour, IControl
{
    [SerializeField] private LoginUI Login;
    [SerializeField] private SceneLogic Scene;
    [SerializeField] private PlayerMoveMent Movement;

    private GameClient Client = null;

    private void Awake()
    {
        Application.targetFrameRate = 1024;

        Login.ActionLogin = (ip, port, name, passwd) =>
        {
            if (Client != null)
            {
                NetDebug.Log("已经连接成功~~~");
                return;
            }

            Client = new GameClient();
            if (!Client.Start(ip, port, name, passwd, this))
            {
                NetDebug.Log("连接服务器失败~~~");
                return;
            }

            Client.DisconnectCallback = () => { Disconnect(0); };

            Movement.ClientLogic = Client;
        };
    }

    public void Disconnect(long userId)
    {
        if (userId == 0)
        {
            Client.Destroy();
            Client = null;

            Login.gameObject.SetActive(true);
        }
        else
        {
            Scene.RemovePlayer(userId);
        }
    }

    private void Update()
    {
        Client?.Update();
    }

    public void ServerStatusChanged(int count)
    {
        NetDebug.Log($"ServerStatusChanged:{count}");
    }

    public void LoginResult(S2CLoginRes loginres)
    {
        if (loginres.ErrCode != 0)
        {
            return;
        }
        Login.gameObject.SetActive(false);

        foreach (var player in loginres.DictMoveData)
        {
            Scene.AddPlayer(player.Key, player.Value);
        }
    }

    public void OtherUserLogin(long userId, string Name)
    {
        NetDebug.Log($"OtherUserLogin:{userId}--{Name}");
        Scene.AddPlayer(userId, null);
    }

    public void PlayerMove(long userId, MoveData data)
    {
        Scene.MovePlayer(userId, data);
    }

    public void Chat(long userId, string msg)
    {
    }
}
